from django.shortcuts import render
from django.views import View
from orders.models import OrderInfo
from django import http
from qingmei_mall.utils.response_code import RETCODE
from alipay import AliPay
from django.conf import settings
from .models import Payment
import os




# 生成支付地址
class AlipayUrlView(View):
    def get(self,request,order_id):
        # 验证
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except:
            return http.JsonResponse({"code":RETCODE.PARAMERR,"errmsg":"无效的订单编号"})
        # 处理
        # 创建alipay对象
        alipay = AliPay(
            appid=settings.APP_ID,  # 应用id
            app_notify_url=None,  # 默认回调url
            app_private_key_string=settings.APP_PRIVATE_KEY,  # 应用公钥
            alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY, # alipay公钥
            sign_type="RSA2", # 签名方式
            debug=settings.ALIPAY_DEBUG # 是否调试 沙箱环境为True 真实环境用False
        )
        # 生成支付宝授权地址
        alipay_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id, # 订单编号
            total_amount=str(order.total_amount), # 总金额
            subject="美多商城-支付系统", # 标题
            return_url=settings.ALIPAY_RETURN_URL, # 回调地址
        )
        alipay_url = settings.ALIPAY_URL + "?" + alipay_string
        # 响应
        return http.JsonResponse({"code":RETCODE.OK,"errmsg":"OK","alipay_url":alipay_url})

# 保存支付宝流水号
class AlipaySaveView(View):
    def get(self,request):
        # 接收
        data = request.GET  # QueryDict alipay的verify不支持该类型
        data = data.dict() # 将QueryDict 转换为python中的dict类型
        # 删除字典中的sign
        signature = data.pop("sign")
        # 处理
        # 创建alipay对象，调用verify方法校验此次交易是否成功


        # 创建alipay对象
        alipay = AliPay(
            appid=settings.APP_ID,  # 应用id
            app_notify_url=None,  # 默认回调url
            app_private_key_string=settings.APP_PRIVATE_KEY,  # 应用公钥
            alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY, # alipay公钥
            sign_type="RSA2", # 签名方式
            debug=settings.ALIPAY_DEBUG # 是否调试 沙箱环境为True 真实环境用False
        )
        # 参数1：字典 参数2：秘钥
        success = alipay.verify(data,signature)
        # 如果成功
        if success:
            # 保存支付流水号
            # 订单编号
            order_id = data.get("out_trade_no")
            # 流水号
            trade_id = data.get("trade_no")
            Payment.objects.create(order_id=order_id,trade_id=trade_id)
            # 修改订单状态为待发货
            order = OrderInfo.objects.get(order_id=order_id)
            order.status = 2
            order.save()
            context = {
                'trade_id': trade_id
            }
            return render(request, 'pay_success.html', context)
        # 如果失败
        else:
            return http.HttpResponseForbidden('非法请求')